package tp1.presentacion.controlador;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tp1.presentacion.modelo.Tren;
import tp1.presentacion.modelo.TrenLogic;

/**
 * Servlet implementation class TrenController
 */
public class TrenController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TrenController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = request.getPathInfo();
		if(url.equals("/listar")) {
			this.listarTrenes(request, response);
		} else if(url.equals("/nuevo")) {
			response.sendRedirect("nuevoTren.jsp");
		} else if(url.equals("/registrar")) {
			this.registrarTren(request, response);
		}
	}
	
	private void registrarTren(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		TrenLogic trLog = new TrenLogic();
		String nombre = request.getParameter("nombre");
		float precio = Float.parseFloat(request.getParameter("precio"));
		Tren tr = new Tren();
		tr.setCodigo(0);
		tr.setNombre(nombre);
		tr.setPrecio(precio);
		trLog.agregar(tr);
		response.sendRedirect("index.jsp");
	}
	private void listarTrenes(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		TrenLogic trLog = new TrenLogic();
		ArrayList<Tren> trs = trLog.getTodos();
		request.setAttribute("trenes", trs);
		RequestDispatcher rdis = request.getRequestDispatcher("/listTrenes.jsp");
		rdis.forward(request, response);		
	}
}